/*
* SMILParser
*
* Version 1.0
*
* Programmers: Jesse Louderback, Noah Pham, Chad Carpenter, and Marc Hindman
*/
package Message;

import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.util.Log;

public class SMILAudio {
	private MediaPlayer mediaPlayer;
	private int playbackPosition = 0;
	private float startTime = 0.0f;
	private float endTime = 0.0f;
	private String region;
	private String data;
	private boolean bufferedEnough = false;

	public String test() {
		return mediaPlayer.isPlaying() + "";
	}

	public SMILAudio(SMILObject ob) {
		startTime = ob.startTime;
		endTime = ob.endTime + ob.startTime;
		region = ob.region;
		data = ob.data;
		try {
			getAudio(data);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void pause() {
		if (mediaPlayer != null) {
			playbackPosition = mediaPlayer.getCurrentPosition();
			mediaPlayer.pause();
		}
	}

	public void playAudio() {
		try {
			if (!mediaPlayer.isPlaying()) {
				mediaPlayer.setVolume(1.0f, 1.0f);
				mediaPlayer.start();
			}
		} catch (Exception e) {}
	}

	public void stopAudio() {
		mediaPlayer.stop();
	}

	private void getAudio(String url) throws Exception {
		killMediaPlayer();
		mediaPlayer = new MediaPlayer();
		mediaPlayer.setDataSource(url);
		mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
		
		//mediaPlayer.prepare();
		mediaPlayer.prepareAsync();
		mediaPlayer.setOnBufferingUpdateListener(new OnBufferingUpdateListener(){

			public void onBufferingUpdate(MediaPlayer mp, int percent) {
				Log.e("SMILDIAL", "" + percent);
				if (percent > 40) {
					bufferedEnough = true;
				}
			}
		});
	}

	public void killMediaPlayer() {
		if (mediaPlayer != null) {
			try {
				mediaPlayer.release();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public void setStartTime(float s) {
		startTime = s;
	}

	public float getStartTime() {
		return startTime;
	}

	public void setEndTime(float s) {
		endTime = s;
	}

	public float getEndTime() {
		return endTime;
	}

	public void resetAudio() {
		mediaPlayer.seekTo(0);
		mediaPlayer.pause();
	}

	public boolean getReady(){
		return bufferedEnough;
	}
	@Override
	public String toString() {
		return "<audio region=\"" + region + "\" src=\"" + data + "\" begin=\""
				+ startTime + "\" dur=\"" + endTime + "\" />";
	}
}
